package model

import (
	"fmt"
	"strings"
	"usplatformserver/global"

	"github.com/jinzhu/gorm"
)

type PatientImageInfo struct {
	PatientStamp        string `json:"patientStamp" gorm:"Column:patientStamp"`
	ImageId             int    `json:"imageId" gorm:"Column:imageId"`
	ImageType           int    `json:"imageType" gorm:"Column:imageType"`
	ImageUrl            string `json:"imageName" gorm:"Column:imageName"`
	ImageWidth          int    `json:"imageWidth" gorm:"Column:imageWidth"`
	ImageHeight         int    `json:"imageHeight" gorm:"Column:imageHeight"`
	ImageThumbnilUrl    string `json:"imageThumbnilName" gorm:"Column:imageThumbnilName"`
	ImageThumbnilWidth  int    `json:"imageThumbnilWidth"`
	ImageThumbnilHeight int    `json:"imageThumbnilHeight"`
	ImageNTPStamp       string `json:"imageNTPStamp" gorm:"Column:imageNTPStamp"`
}

type PatientImageListSwagger struct {
	*SwaggerSuccess
	Data *PatientImageInfo `json:"data"`
}

// 查询图片列表
func (t PatientInfo) GetImageList(db *gorm.DB) ([]*PatientImageInfo, error) {
	var images []*PatientImageInfo = nil
	var query string
	if CheckpointThyroid == t.OrganType {
		query = fmt.Sprintf("call selectPatientImages(%s)", t.TimeStamp)
	} else if CheckpointBreast == t.OrganType {
		query = fmt.Sprintf("call selectPatientBreastImages(%s)", t.TimeStamp)
	}

	res := db.Raw(query).Scan(&images)
	if res.Error != nil {
		return nil, res.Error
	}
	//图片转换处理
	imagesOut := imagesConvert(images)

	return imagesOut, nil
}

// 查询图片组信息
func (t PatientInfo) GetImageGroup(db *gorm.DB, imageId, imageType, bBoxId int) ([]*PatientImageInfo, error) {
	var images []*PatientImageInfo = nil
	query := ""
	if CheckpointThyroid == t.OrganType {
		query = getImageGroupSql("t_tubercle_info", t.TimeStamp, imageId, imageType, bBoxId)
	} else if CheckpointBreast == t.OrganType {
		query = getImageGroupSql("t_breast_tubercle_info", t.TimeStamp, imageId, imageType, bBoxId)
	}

	res := db.Raw(query).Scan(&images)

	if res.Error != nil {
		return nil, res.Error
	}

	//图片转换处理
	imagesOut := imagesConvert(images)

	//如果是冻结图像，只传第一张
	if imageType == ImageTypeFreeze && len(imagesOut) > 0 {
		images = nil
		images = append(images, imagesOut[0])
		imagesOut = images
	}

	return imagesOut, nil
}

// 查询甲状腺图片列表（按时间倒序）
func (t PatientInfo) GetThyroidImageListDescByTime(db *gorm.DB) ([]*PatientImageInfo, error) {
	return getImageListDescByTime(db, "t_tubercle_info", t.TimeStamp)
}

// 查询乳腺图片列表（按时间倒序）
func (t PatientInfo) GetBreastImageListDescByTime(db *gorm.DB) ([]*PatientImageInfo, error) {
	return getImageListDescByTime(db, "t_breast_tubercle_info", t.TimeStamp)
}

func imagesConvert(images []*PatientImageInfo) []*PatientImageInfo {
	var imgPath1 = fmt.Sprintf("%s/patientInfo", global.AppSettings.UsclientPath)
	thumbnilNameTmp := ""
	imageNameTmp := ""
	for i := range images {
		//本地路径转网络路径
		thumbnilNameTmp = strings.Replace(images[i].ImageThumbnilUrl, imgPath1, "/img", 1)
		images[i].ImageThumbnilUrl = thumbnilNameTmp
		imageNameTmp = strings.Replace(images[i].ImageUrl, imgPath1, "/img", 1)
		images[i].ImageUrl = imageNameTmp
		images[i].ImageThumbnilWidth = 500
		images[i].ImageThumbnilHeight = 252
	}
	return images
}

func getImageListDescByTime(db *gorm.DB, tableName, patientStamp string) ([]*PatientImageInfo, error) {
	var images []*PatientImageInfo = nil
	query := "select f.* from ("
	query += "select b.patientStamp, b.imageId, b.imageType, b.imageName, b.imageThumbnilName,b.imageWidth,b.imageHeight, b.imageNTPStamp,b.bBoxId,b.area,b.tiradsValue "
	query += "from ("
	query += "select a.patientStamp, a.imageId, a.imageType, a.imageName, a.imageThumbnilName, a.imageWidth, a.imageHeight, a.imageNTPStamp,a.bBoxId,a.area,a.tiradsValue,"
	query += "if(@pdept=a.imageId, @rank:=@rank+1, @rank:=1) as r, @pdept:=a.imageId "
	query += "from ("
	query += "select t1.timeStamp as patientStamp, t2.id as imageId, t2.imageType, t2.imageName, t2.imageThumbnilName,t2.imageWidth,t2.imageHeight, t2.imageNTPStamp, t3.bBoxId, t3.area, t3.tiradsValue "
	query += "from t_patient_info t1 "
	query += "left join t_image_info t2 on t1.id=t2.patientId and t2.imageType = 1 "
	query += fmt.Sprintf("left join %s t3 on t1.id=t3.patientId and t2.id = t3.imageId ", tableName)
	query += fmt.Sprintf("where t1.timeStamp = %s and t1.isDelete = 0 and t2.isDelete = 0 and t3.isDelete = 0 ", patientStamp)
	query += "order by t2.id asc, t3.tiradsValue desc, t3.area desc, t2.imageNTPStamp desc "
	query += ") as a,"
	query += "(select @pdept := null ,@rank:=0) a1"
	query += ") as b where r <= 1"

	query += " union all "

	query += "select b.patientStamp, b.imageId, b.imageType, b.imageName, b.imageThumbnilName,b.imageWidth,b.imageHeight, b.imageNTPStamp, b.bBoxId, b.area, b.tiradsValue from "
	query += "("
	query += "select a.patientStamp, a.imageId, a.imageType, a.imageName, a.imageThumbnilName,a.imageWidth,a.imageHeight, a.imageNTPStamp, a.bBoxId, a.area, a.tiradsValue, if(@pdept=a.bBoxId, @rank:=@rank+1, @rank:=1) as r, @pdept:=a.bBoxId "
	query += "from ("
	query += "select t1.timeStamp as patientStamp, t2.id as imageId, t2.imageType, t2.imageName, t2.imageThumbnilName,t2.imageWidth,t2.imageHeight, t2.imageNTPStamp, t3.bBoxId, t3.area, t3.tiradsValue "
	query += "from t_patient_info t1 "
	query += "left join t_image_info t2 on t1.id = t2.patientId and t2.imageType = 0 "
	query += fmt.Sprintf("left join %s t3 on t1.id = t3.patientId and t2.id = t3.imageId ", tableName)
	query += fmt.Sprintf("where t1.timeStamp = %s and t1.isDelete = 0 and t2.isDelete = 0 and t3.isDelete = 0 ", patientStamp)
	query += "order by t3.bBoxId asc, t3.tiradsValue desc, t3.area desc, t2.imageNTPStamp asc "
	query += ") a,"
	query += "(select @pdept:= null ,@rank:=0) a1) as b where r <= 1 "
	query += "order by imageNTPStamp desc"
	query += ") as f order by imageNTPStamp desc;"

	res := db.Raw(query).Scan(&images)

	if res.Error != nil {
		return nil, res.Error
	}

	//图片转换处理
	imagesOut := imagesConvert(images)

	return imagesOut, nil
}

func getImageGroupSql(tableName, patientStamp string, imageId, imageType, bBoxId int) string {
	query := "select t2.id as imageId, t2.imageType, t2.imageName, t2.imageThumbnilName,t2.imageWidth,t2.imageHeight,t2.imageNTPStamp, t1.timeStamp as patientStamp,t3.tiradsValue,t3.area "
	query += "from t_patient_info t1 "
	query += "left join t_image_info t2 on t1.id = t2.patientId "
	query += fmt.Sprintf("left join %s t3 on t3.imageId = t2.id and t3.patientId = t1.id ", tableName)
	query += fmt.Sprintf("where t1.timeStamp=%s and t2.imageType=%d and t1.isDelete = 0 and t2.isDelete=0 and t3.isDelete = 0 ", patientStamp, imageType)
	if imageType == ImageTypeScan {
		query += fmt.Sprintf("and t3.bBoxId=%d ", bBoxId)
	} else if imageType == ImageTypeFreeze {
		query += fmt.Sprintf("and t2.id=%d ", imageId)
	}
	query += "order by tiradsValue desc, area desc, imageNTPStamp asc;"

	return query
}
